package org.proxy;

import java.util.List;

import org.dao.UserDAO;
import org.dbc.DatabaseConnection;
import org.hibernate.Session;
import org.impl.UserDAOImpl;
import org.vo.User;

public class UserDAOProxy implements UserDAO{
   private Session session;
   private UserDAO dao=null;
   public UserDAOProxy() throws Exception{
	   this.session=DatabaseConnection.getSession();
	   this.dao=new UserDAOImpl(this.session);
	   
   }
	@Override
	public boolean doCreate(User user) throws Exception {
		// TODO Auto-generated method stub
		boolean flag=false;
		try{
			 this.session.beginTransaction();
			 flag=this.dao.doCreate(user);
			 this.session.getTransaction().commit();
			 if(this.session!=null&&this.session.isOpen())
				 this.session.close();
			
		}catch(Exception e){
			flag=false;
			this.session.getTransaction().rollback();
		}
		return flag;
	}

	@Override
	public List<User> findAll() throws Exception {
		// TODO Auto-generated method stub
		List<User> list=null;
		try{
			this.session.beginTransaction();
			list=this.dao.findAll();
			this.session.getTransaction().commit();
			 if(this.session!=null&&this.session.isOpen())
				 this.session.close();
		}catch(Exception e){
			   this.session.getTransaction().rollback();
			   throw e;
		}
		return list;
	}

	@Override
	public User findById(int id) throws Exception {
		// TODO Auto-generated method stub
		User user=null;
		try{
			this.session.beginTransaction();
			user=this.dao.findById(id);
			this.session.getTransaction().commit();
			if(this.session!=null&&this.session.isOpen())
		         this.session.close();    
		}catch(Exception e){
			this.session.getTransaction().rollback();
			throw e;
		}
		return user;
	}
	@Override
	public boolean update(User user) throws Exception {
		// TODO Auto-generated method stub
		boolean flag=false;
		try{
			this.session.beginTransaction();
			flag=dao.update(user);
			this.session.getTransaction().commit();
			if(this.session!=null&&this.session.isOpen())
				 this.session.close();
			
		}catch(Exception e){
			flag=false;
			this.session.getTransaction().rollback();
		}
		return flag;
	}

}
